package com.bj58.ecdata.monitor.monitor;

import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.bj58.ecdata.monitor.service.SMS;
import com.bj58.ecdata.redis.JedisX;
import com.bj58.ecdata.util.NumberUtils;
import com.google.common.collect.Lists;

/**
 * 检查当前时间和redis的最近更新时间是否差距太大
 * @author lichao
 * @date 2014年8月21日
 */
@Component
public class RedisMonitor {
	static Logger log = LoggerFactory.getLogger(RedisMonitor.class);
	// public static String zkAddress =
	// "10.5.20.18:2181,10.5.20.100:2181,10.4.17.71:2181";
	// public static String projectName = "opt";
	// private CuratorFramework client;

	@Autowired
	@Qualifier("cachePool")
	protected JedisX jedis;
	private List<String> cacheKeys = Lists.newArrayList();
	private static final long _2m = 1000 * 60 * 2;
	private static final long _10m = 1000 * 60 * 10;

	public static final FastDateFormat dateFormat = FastDateFormat.getInstance("MM-dd HH:mm:ss");

	@PostConstruct
	public void init() {
		// CuratorFrameworkFactory.Builder builder =
		// CuratorFrameworkFactory.builder();
		// client =
		// builder.connectString(zkAddress).sessionTimeoutMs(10000).connectionTimeoutMs(5000).canBeReadOnly(false)
		// .retryPolicy(new ExponentialBackoffRetry(1000,
		// Integer.MAX_VALUE)).namespace(projectName).defaultData(null).build();
		// client.start();

		cacheKeys.add("track_latest");
		cacheKeys.add("display_latest");
		cacheKeys.add("click_latest");
		cacheKeys.add("info_latest");
		cacheKeys.add("resume_latest");

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						Thread.sleep(_10m);
						process();
					} catch (Exception e) {
						log.error("run RedisMonitor process error", e);
					}
				}
			}
		}).start();
	}

	private static String messagePattern = "%s now:%s, redis:%s";

	private void process() {
		log.info("check redis key latest time:");
		for (String key : cacheKeys) {
			try {
				jedis.getString(key);
				long latest = NumberUtils.toLong(jedis.getString(key));
				long now = System.currentTimeMillis();
				//相差两分钟则发短信预警
				if (now - latest > _2m) {
					String message = String.format(messagePattern, key, dateFormat.format(now), dateFormat.format(latest));
					SMS.defaultSend(message);
				}
				log.info("check redis latest time, key:{}, redis:{}", key, dateFormat.format(latest));
			} catch (Exception e) {
				log.error("check latest error!", e);
			}
		}

	}

}